#include "sqlite.hpp"
#include <cassert>
#include <vector>
typedef struct strdent
{
    int sn;
    std::string name;
    int age;
} stu;
// 回调函数会被 SQLite 调用多次，每次调用时会传递一行查询结果
// fields 字符串指针数组 每一个元素就是数据库每一列的字段名(字符串)指针
// result也是类似, 每一个元素就是一个字符串指针, 指向对应字段的数据
int select_stu_callback(void *arg, int col, char** result, char** fields)
{
    std::vector<stu>* students = static_cast<std::vector<stu>*>(arg);  
    
    stu s;  
    // 循环遍历每一列
    for (int i = 0; i < col; i++) {  
        if (std::string(fields[i]) == "sn") {  
            s.sn = std::atoi(result[i]); // 将字符串转换为整数  
        } else if (std::string(fields[i]) == "name") {  
            s.name = result[i];
        }  
        else if(std::string(fields[i]) == "age")
        {
            s.age = std::atoi(result[i]);
        }
    }  
    
    students->push_back(s);  
    return 0; // 返回 0 表示继续 

}
int main()
{
    SqliteHelper helper("./test.db");
    // 打开数据库
    assert(helper.open());
    // 创建表
    const char * create_table = "create table if not exists student(sn int primary key, name varchar(32), age int);";
    assert(helper.exec(create_table, nullptr, nullptr));
    // 插入 修改 删除 查询
    // 插入
    // const char *insert_sql = "insert into student values(1, '张三', 18), (2, '李四', 19), (3, '王五', 19);";
    // assert(helper.exec(insert_sql, nullptr, nullptr));

    // 修改
    // const char *update_sql = "update student set name='zhangsan' where sn=1;";
    // assert(helper.exec(update_sql, nullptr, nullptr));

    // 删除
    // const char *delete_sql = "delete from student where sn=3;";
    // assert(helper.exec(delete_sql, nullptr, nullptr));

    // 查询
    const char *select_sql = "select * from student;";
    std::vector<stu> arr;
    // 这里arr的地址对应回调函数的arg
    assert(helper.exec(select_sql, select_stu_callback, &arr));

    for (auto &stu : arr) {
        std::cout << stu.sn  << ", " << stu.name << ", " << stu.age <<std::endl;
    }
    // 关闭数据库
    helper.close();
    return 0;
}
